//
//  SoapUtil.swift
//  万才信息App
//
//  Created by 陌上互联  on 16/7/13.
//  Copyright © 2016年 万才信息. All rights reserved.
//

import Foundation
import SOAPEngine64

class soapUtil {
    
//    amsx的url地址
    var asmxURL:String=""
//    method的url地址
    var methodURL:String=""
//    method的名称
    var methodName:String=""
    
//    URL location of soap
    let SOAP_URL="http://58.215.179.167/"
    let NAMESPACE="http://tempuri.org/"
    
//    soap object of soapEngine
    let soap=SOAPEngine()
    
    init(){
//        default config of soap engine
        soap.userAgent="SOAPEngine"
        soap.actionNamespaceSlash=true
        soap.version=SOAPVersion.VERSION_1_1
        soap.responseHeader=true
    }
    
//    添加一个参数
    func addParam(key:String,value:String){
        soap.setValue(value,forKey: key)
        print("Add key: "+key+"->"+value)
    }
    
//    设置asmxName和methodName
    func setName(asmxName:String,methodName:String){
        asmxURL=SOAP_URL+asmxName
        self.methodName=methodName
        methodURL=NAMESPACE+methodName
        print("New soap!")
        print(asmxName+"/"+methodName)
    }
    
//    清空参数列表
    func clearParams(){
        soap.clearValues()
    }
    
//    发送soap请求
    func send(successCallback:(data:JSON)->Void,failCallback:(error:NSString!)->Void){
        soap.requestURL(asmxURL,
        soapAction: methodURL,
        completeWithDictionary:
            {(statusCode : Int,dict : [NSObject : AnyObject]!) -> Void in
                let myResponseHeader=self.methodName+"Response"
                let myResultHeader=self.methodName+"Result"
//                print(dict)
                if dict["Body"] != nil{
                    
                    var jsonResult=dict["Body"]![myResponseHeader]!![myResultHeader] as! String
//                    去除html标签
//                    print("去除标签前:")
//                    print(jsonResult)
                    jsonResult=checkUtil.removeHtmlTag(jsonResult)
//                    print("去除后:")
                    jsonResult=checkUtil.removeEnter(jsonResult)
//                    print("去除Enter:")
//                    print(jsonResult)
                    //解析json数据
                    if let dataFromString=jsonResult.dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: false){
                        let json=JSON(data:dataFromString)
                        print("获取数据：")
                        print(json)
                        successCallback(data: json)
                    }else{
                        failCallback(error:"json解析失败")
                    }
                }else{
                    print("获取数据有问题！")
                    print(dict)
                }
                       }) { (error : NSError!) -> Void in
            failCallback(error: error.debugDescription)
            print("%@", error)
        }
    }
    
}
